package io.github.igordonxiao.gateguard.service.impl;

import io.github.igordonxiao.gateguard.config.GuardUser;
import io.github.igordonxiao.gateguard.domain.User;
import io.github.igordonxiao.gateguard.exception.UserExceptions;
import io.github.igordonxiao.gateguard.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 验证用户
 */
@Service
public class UserOauthServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * 用户授权
     * 简化处理
     */
    private final List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<SimpleGrantedAuthority>() {{
        add(new SimpleGrantedAuthority("Admin"));
    }};

    @Override
    public UserDetails loadUserByUsername(@NotNull String username) {
        // 登录使用code字段
        User user = userService.findUserByCode(username);
        if (user == null) {
            throw UserExceptions.USER_NOT_FOUND;
        }
        GuardUser guardUser = new GuardUser(user.getName(), user.getPassword(), grantedAuthorities);
        guardUser.setId(user.getId());
        guardUser.setCode(user.getCode());
        return guardUser;
    }
}